package com.ktjiaoyu.t313.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ktjiaoyu.t313.pojo.SysRole;
import com.ktjiaoyu.t313.pojo.SysUser;
import com.ktjiaoyu.t313.service.RoleService;
import com.ktjiaoyu.t313.service.UserService;
import com.ktjiaoyu.t313.utils.PageSupport;
import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.List;

/**
 * 用户Controller
 */
@Controller
@RequestMapping("/user")
public class UserController {

    Logger logger = Logger.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;


    /**
     * 查询用户列表
     * @param model
     * @param queryRealName
     * @param queryRoleId
     * @param pageIndex
     * @return
     */
    @GetMapping("/list")
    public String getUserList(Model model, String queryRealName, Integer queryRoleId
            , @RequestParam(defaultValue = "1") Integer pageIndex){
        List<SysUser> userList = null;
        try{
            //设置页面容量
            int pageSize = 10;
            //总数量（表）
            int totalCount	= userService.getUserCount(queryRealName,queryRoleId);
            //总页数
            PageSupport pages=new PageSupport();
            pages.setCurrentPageNo(pageIndex);
            pages.setPageSize(pageSize);
            pages.setTotalCount(totalCount);
            int totalPageCount = pages.getTotalPageCount();
            //控制首页和尾页
            if(pageIndex > totalPageCount){
                pageIndex = totalPageCount;
                throw new RuntimeException("页码不正确");
            }
            userList = userService.getUserList(queryRealName,queryRoleId,pageIndex,pageSize);
            model.addAttribute("userList", userList);
            List<SysRole> roleList = null;
            roleList = roleService.getRoleList();
            model.addAttribute("roleList", roleList);
            model.addAttribute("queryRealName", queryRealName);
            model.addAttribute("queryRoleId", queryRoleId);
            model.addAttribute("totalPageCount", totalPageCount);
            model.addAttribute("totalCount", totalCount);
            model.addAttribute("currentPageNo", pageIndex);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("用户列表接口访问失败");
            return "redirect:/user/toSysError";
        }
        return "sysUser/list";
    }

    /**
     * 跳转到异常处理页面
     * @return
     */
    @RequestMapping(value="/toSysError")
    public String sysError(){
        return "sysError";
    }

    @RequestMapping(value = "/toAdd")
    public String toAdd(){

        return "sysUser/add";
    }


    /**
     * 新增用户
     * @param user
     * @return
     */
    @RequestMapping(value = "/add")
    public String addUser(SysUser user, @RequestParam(value = "idPic",required = false) MultipartFile file, HttpServletRequest request){

        String idPicPath = null;    //上传后的文件路径，需要保存到数据库中
        //判断上传文件是否为空
        if(!file.isEmpty()){
            //定义上传文件的存储路径，上传的文件全部保存在这个目录下
            String path = request.getSession().getServletContext().getRealPath("statics"+ File.separator+"uploadfiles");
            logger.info("上传文件路径："+path);
            //获取源文件名
            String originalFile = file.getOriginalFilename();
            logger.info("源文件名："+originalFile);
            //获取原文件名后缀
            String prefix = FilenameUtils.getExtension(originalFile);
            logger.info("原文件名后缀："+prefix);
            //定义文件上传大小，超过该大小提示不可上传
            //5000000byte/1024 5000K/1024 = 5M
            int filesSize = 5000000;
            //判断文件大小
            if(file.getSize()>filesSize){
                request.setAttribute("uploadFileError","文件大小不得超过5M");
                return "sysUser/add";
            }else if(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
                    || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")){
                //判断文件名后缀，因为是图片，所以必须是以上几种后缀格式
                //为了保证文件不重复，重新生成新的文件名
                //此处生成规则：系统时间戳+随机数+_Person.+后缀名
                String fileName = System.currentTimeMillis()+"_Personal."+prefix;
                logger.info("新生成的文件名为："+fileName);
                //创建文件对象
                File targetFile = new File(path);
                //如果文件路径不存在，则创建目录
                if(!targetFile.exists()){
                    targetFile.mkdirs();
                }
                //保存
                try {
                    file.transferTo(new File(targetFile,fileName));
                } catch(Exception ex){
                    ex.printStackTrace();
                    request.setAttribute("uploadFileError","上传失败！");
                    return "sysUser/add";
                }
                //保存文件所在路径，便于后续保存在数据库中
                idPicPath = File.separator+"static"+File.separator+"uploadFiles"+File.separator+fileName;

            }else{
                request.setAttribute("uploadFileError","上传图片格式不正确！");
                return "sysUser/add";
            }
        }
        //对上传文件的数据进行处理之前，先判断是否为空，若为空，则跳过上传文件的处理
        //此处是继续添加除图片之外的其他数据字段
        user.setIdPicPath(idPicPath);
        //新增成功跳转到用户列表
        if(userService.addUser(user)>=1){
            return "redirect:/user/list";
        }

        return "redirect:/user/toAdd";
    }

    /**
     * 验证用户编号是否已存在
     * @param account
     * @return
     */
    @ResponseBody
    @GetMapping("/userExist")
    public Object userExist(@RequestParam(required = true) String account)throws Exception {
        logger.debug("验证用户名account="+account + "的用户是否存在");
        HashMap<String, Object> resultMap = new HashMap<String, Object>();
        try{
            // 角色编号不可为空
            if(account == null || "".equals(account.trim())){
                resultMap.put("exist", -1);
                resultMap.put("msg", "用户名不可以为空");
            }else {
                SysUser sysUser = userService.selectByAccount(account);
                if(null != sysUser) {
                    resultMap.put("exist", 1);  //用户名已存在
                }else {
                    resultMap.put("exist", 0);  //用户名可以使用
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return JSONArray.toJSONString(resultMap);
    }

    /**
     * 查询用户详情
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/view/{id}")
    public String view(@PathVariable Integer id, Model model)throws Exception {
        logger.debug("根据id查询用户详情"+id);
        SysUser sysUser = userService.getUserById(id);
        model.addAttribute(sysUser);
        return "sysUser/view";
    }

    /**
     * 查询用户详情
     * @param id
     * @param model
     * @return
     */
    @GetMapping(value = "/{id}/view")
    @ResponseBody
    public Object view2(@PathVariable Integer id, Model model)throws Exception {
        logger.debug("根据id查询用户详情"+id);
        String userJson = "";
        if(id == null || "".equals(id)){
            return "nodata";
        }
        SysUser sysUser = userService.getUserById(id);
        //将获取到的用户对象转成JSON字符串返回给前端页面
        userJson = JSON.toJSONString(sysUser);
        return userJson;
    }


}
